<script setup lang="ts">
import type { Category, Product } from '@/types/mall'
import { formatPrice } from '@/utils/mall'

const router = useRouter()
const cartStore = useCartStore()

// 搜索关键词
const searchKeyword = ref('')

// 顶部分类图标
const topCategories = [
  { id: '1', name: '水果', icon: '🍎', color: 'from-red-400 to-pink-400', bgColor: 'bg-red-50' },
  { id: '2', name: '蔬菜', icon: '🥬', color: 'from-green-400 to-emerald-400', bgColor: 'bg-green-50' },
  { id: '3', name: '零食', icon: '🍿', color: 'from-yellow-400 to-orange-400', bgColor: 'bg-yellow-50' },
  { id: '4', name: '肉蛋', icon: '🥩', color: 'from-red-500 to-rose-500', bgColor: 'bg-red-50' },
  { id: '5', name: '乳品', icon: '🥛', color: 'from-blue-400 to-cyan-400', bgColor: 'bg-blue-50' },
  { id: '6', name: '速食', icon: '🍜', color: 'from-orange-400 to-amber-400', bgColor: 'bg-orange-50' },
  { id: '7', name: '粮油', icon: '🌾', color: 'from-yellow-500 to-amber-500', bgColor: 'bg-yellow-50' },
  { id: '8', name: '饮品', icon: '🧃', color: 'from-purple-400 to-violet-400', bgColor: 'bg-purple-50' },
]

// 侧边栏状态
const active = ref<number>(0)
const scrollTop = ref<number>(0)
const itemScrollTop = ref<number[]>([])

// 加载状态
const loading = ref(true)
const topCategoriesLoading = ref(true)
const leftCategoriesLoading = ref(true)
const productsLoading = ref(true)

// 排序选项
const sortOptions = [
  { label: '综合排序', value: 'default' },
  { label: '价格从低到高', value: 'price_asc' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '销量从高到低', value: 'sales_desc' },
]

const currentSort = ref('default')
const showSortSheet = ref(false)

// 创建更多商品数据的辅助函数
function createProducts(categoryId: string, count: number = 12): Product[] {
  const products: Product[] = []
  const productTemplates = [
    { name: 'iPhone 15 Pro Max', desc: '搭载A17 Pro芯片，顶级性能体验', basePrice: 999900 },
    { name: 'Samsung Galaxy S24', desc: '旗舰级拍照，AI智能体验', basePrice: 799900 },
    { name: 'MacBook Air M3', desc: 'M3芯片强劲性能，轻薄便携', basePrice: 899900 },
    { name: 'iPad Pro 12.9', desc: 'M2芯片，专业级平板体验', basePrice: 699900 },
    { name: 'AirPods Pro', desc: '主动降噪，沉浸式音质', basePrice: 179900 },
    { name: 'Apple Watch Ultra', desc: '运动健康，专业级智能手表', basePrice: 619900 },
    { name: 'Dell XPS 13', desc: '商务办公，性能出色', basePrice: 899900 },
    { name: 'LG 27寸 4K显示器', desc: '4K超清，专业显示器', basePrice: 299900 },
  ]
  
  for (let i = 0; i < count; i++) {
    const template = productTemplates[i % productTemplates.length]
    const variation = i > 7 ? ` ${Math.floor(i / 8) + 1}` : ''
    products.push({
      id: `${categoryId}-${i + 1}`,
      name: template.name + variation,
      description: template.desc,
      categoryId,
      images: ['https://via.placeholder.com/300x300?text=' + encodeURIComponent(template.name)],
      defaultPrice: template.basePrice + (Math.random() * 100000),
      originalPrice: template.basePrice + (Math.random() * 200000) + 100000,
      sales: Math.floor(Math.random() * 2000) + 100,
      stock: Math.floor(Math.random() * 100) + 10,
      status: 'active',
      rating: 4.0 + Math.random(),
      reviewCount: Math.floor(Math.random() * 1000) + 50,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    })
  }
  return products
}

// 左侧分类数据
const leftCategories = [
  { id: 'all', name: '全部', icon: '📋', color: 'text-blue-600', count: 2436 },
  { id: 'leaf', name: '叶菜', icon: '🥬', count: 328 },
  { id: 'root', name: '根茎类', icon: '🥕', count: 156 },
  { id: 'fruit-veg', name: '茄果类', icon: '🍅', count: 89 },
  { id: 'beans', name: '豆菌类', icon: '🫘', count: 67 },
  { id: 'seasoning', name: '调味菜', icon: '🧄', count: 45 },
  { id: 'others', name: '其他蔬菜', icon: '🌿', count: 234 },
]

// 商品数据
const products = ref([
  {
    id: '1',
    name: '【限时秒杀】有机糯米笋 炭烤笋尖嫩笋干 农家原味',
    description: '剩余时间 07:18:18',
    images: ['https://via.placeholder.com/200x200/f8fafc/64748b?text=糯米笋'],
    currentPrice: 3070,
    originalPrice: 4340,
    discount: 29,
    tag: '秒杀',
    tagColor: 'bg-gradient-to-r from-red-500 to-pink-500',
    priceLabel: '近期低价',
    sales: 1284,
    rating: 4.9,
    stock: 156
  },
  {
    id: '2', 
    name: '【秒杀爆款】糯米笋嫩笋尖 新鲜笋丝 免泡发湿笋片',
    description: '剩余时间 07:18:18',
    images: ['https://via.placeholder.com/200x200/f8fafc/64748b?text=笋片'],
    currentPrice: 3380,
    originalPrice: 5520,
    discount: 39,
    tag: '秒杀',
    tagColor: 'bg-gradient-to-r from-red-500 to-pink-500',
    priceLabel: '近期低价',
    sales: 967,
    rating: 4.8,
    stock: 89
  },
  {
    id: '3',
    name: '【秒杀特价】东北玉米 新鲜现摘 黏甜黑糯玉米',
    description: '剩余时间 07:18:18', 
    images: ['https://via.placeholder.com/200x200/f8fafc/64748b?text=玉米'],
    currentPrice: 4900,
    originalPrice: 6490,
    discount: 25,
    tag: '秒杀',
    tagColor: 'bg-gradient-to-r from-red-500 to-pink-500',
    priceLabel: '近期低价',
    sales: 2156,
    rating: 4.9,
    stock: 234
  },
  {
    id: '4',
    name: '【限量抢购】山东生姜 老姜大姜 新鲜农家黄姜',
    description: '剩余时间 07:18:18',
    images: ['https://via.placeholder.com/200x200/f8fafc/64748b?text=生姜'],
    currentPrice: 2210,
    originalPrice: 2480,
    discount: 11,
    tag: '秒杀',
    tagColor: 'bg-gradient-to-r from-red-500 to-pink-500',
    priceLabel: '近期低价',
    sales: 567,
    rating: 4.7,
    stock: 78
  },
  {
    id: '5',
    name: '正宗铁棍山药 新鲜铁杆淮山 农家小白嘴山药',
    description: '先用后付 | 回头客7万+',
    images: ['https://via.placeholder.com/200x200/f8fafc/64748b?text=山药'],
    currentPrice: 2065,
    originalPrice: 2634,
    discount: 22,
    tag: '精选',
    tagColor: 'bg-gradient-to-r from-orange-400 to-amber-400',
    priceLabel: '品质优选',
    sales: 3456,
    rating: 4.9,
    stock: 345
  },
  {
    id: '6',
    name: '有机小白菜 新鲜嫩叶菜 无公害绿色蔬菜',
    description: '当日现采 | 新鲜直达',
    images: ['https://via.placeholder.com/200x200/f8fafc/64748b?text=小白菜'],
    currentPrice: 890,
    originalPrice: 1200,
    discount: 26,
    tag: '新鲜',
    tagColor: 'bg-gradient-to-r from-green-400 to-emerald-400',
    priceLabel: '当日特价',
    sales: 789,
    rating: 4.8,
    stock: 456
  }
])

// 初始化锚点位置
function initScrollTop() {
  nextTick(() => {
    // 使用uni-app的API获取元素位置
    const query = uni.createSelectorQuery()
    query.selectAll('.category').boundingClientRect()
    query.exec((res: any) => {
      if (res && res[0] && Array.isArray(res[0])) {
        itemScrollTop.value = res[0].map((item: any) => item.top || 0)
        if (active.value < itemScrollTop.value.length) {
          scrollTop.value = itemScrollTop.value[active.value] || 0
        }
      }
    })
  })
}

// 处理侧边栏切换
function handleSidebarChange({ value }: { value: number }) {
  active.value = value
  if (itemScrollTop.value[value] !== undefined) {
    scrollTop.value = itemScrollTop.value[value]
  }
}

// 处理滚动事件
function onScroll(e: any) {
  const { scrollTop: currentScrollTop } = e.detail
  const threshold = 50 // 下一个标题与顶部的距离
  
  if (currentScrollTop < threshold) {
    active.value = 0
    return
  }
  
  const index = itemScrollTop.value.findIndex(
    (top) => top > currentScrollTop && top - currentScrollTop <= threshold
  )
  
  if (index > -1) {
    active.value = index
  }
}

// 搜索功能
function onSearch() {
  if (searchKeyword.value.trim()) {
    uni.navigateTo({
      url: `/subPackages/product-package/search/index?keyword=${searchKeyword.value}`
    })
  }
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 选择顶部分类
function selectTopCategory(category: any) {
  uni.vibrateShort({ type: 'light' })
  // TODO: 根据分类筛选商品
  uni.showToast({ title: `${category.name}分类`, icon: 'none' })
}

// 选择左侧分类
function selectLeftCategory(index: number) {
  uni.vibrateShort({ type: 'light' })
  active.value = index
  // TODO: 根据分类加载商品
}

// 跳转到商品详情
function goToProductDetail(productId: string) {
  uni.navigateTo({ url: `/subPackages/product-package/goodsDetail/index?id=${productId}` })
}

// 添加到购物车
function addToCart(product: any) {
  uni.vibrateShort({ type: 'heavy' })
  
  // 构造商品数据结构
  const productData = {
    id: product.id,
    name: product.name,
    description: product.description || '',
    categoryId: 'vegetables',
    images: product.images,
    defaultPrice: product.currentPrice,
    originalPrice: product.originalPrice,
    sales: product.sales || 0,
    stock: product.stock || 100,
    status: 'active' as const,
    rating: product.rating || 4.5,
    reviewCount: product.reviewCount || 0,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }
  
  // 添加到购物车 - 使用与其他页面一致的方式
  try {
    (cartStore as any).addToCart(productData)
  } catch (error) {
    console.error('添加到购物车失败:', error)
    uni.showToast({ title: '添加失败', icon: 'none' })
  }
}

// 格式化价格显示
function formatPriceDisplay(price: number): string {
  return (price / 100).toFixed(1)
}

// 计算折扣百分比
function calculateDiscount(currentPrice: number, originalPrice: number): number {
  if (!originalPrice || originalPrice <= currentPrice) return 0
  return Math.round(((originalPrice - currentPrice) / originalPrice) * 100)
}

// 显示排序选择
function showSortOptions() {
  showSortSheet.value = true
}

// 选择排序方式
function selectSort(sortValue: string) {
  currentSort.value = sortValue
  showSortSheet.value = false
  
  // TODO: 根据排序重新获取商品列表
  uni.showToast({ title: `已切换为${sortOptions.find(s => s.value === sortValue)?.label}`, icon: 'none' })
}

// 页面生命周期
onMounted(() => {
  initScrollTop()
  loadPageData()
})

// 加载页面数据
function loadPageData() {
  // 模拟加载顶部分类
  setTimeout(() => {
    topCategoriesLoading.value = false
  }, 800)
  
  // 模拟加载左侧分类
  setTimeout(() => {
    leftCategoriesLoading.value = false
  }, 1000)
  
  // 模拟加载商品数据
  setTimeout(() => {
    productsLoading.value = false
    loading.value = false
  }, 1200)
}
</script>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 顶部搜索栏 -->
    <view class="sticky top-0 z-10 bg-white border-b border-gray-100">
      <!-- 搜索栏 -->
      <view class="flex items-center gap-3 p-4">
        <view @click="goBack" class="p-2 -m-2 active:bg-gray-100 rounded-lg transition-colors">
          <wd-icon name="arrow-left" size="20px" color="#374151" />
        </view>
        
        <view class="flex-1 relative">
          <view class="absolute left-3 top-1/2 transform -translate-y-1/2 z-10">
            <wd-icon name="search" size="16px" color="#9ca3af" />
          </view>
          <input 
            v-model="searchKeyword" 
            placeholder="搜索商品" 
            class="w-full h-10 pl-10 pr-4 bg-gray-100 rounded-full text-sm border-none outline-none placeholder-gray-400 focus:bg-white focus:ring-2 focus:ring-blue-500/20 transition-all"
            @confirm="onSearch"
          />
        </view>
      </view>
      
      <!-- 顶部分类图标 -->
      <scroll-view class="pb-3" scroll-x :show-scrollbar="false">
        <view class="flex gap-4 px-4">
          <!-- 顶部分类骨架屏 -->
          <template v-if="topCategoriesLoading">
            <view 
              v-for="n in 8" 
              :key="'skeleton-' + n"
              class="flex flex-col items-center gap-2 min-w-16"
            >
              <wd-skeleton
                :width="48"
                :height="48"
                :round="true"
                :animate="true"
              />
              <wd-skeleton
                :width="32"
                :height="10"
                :round="true"
                :animate="true"
              />
            </view>
          </template>
          
          <!-- 顶部分类数据 -->
          <template v-else>
            <view 
              v-for="(category, index) in topCategories" 
              :key="category.id"
              class="flex flex-col items-center gap-2 min-w-16 active:scale-95 transition-transform"
              @click="selectTopCategory(category)"
            >
              <view class="relative">
                <view 
                  class="w-12 h-12 rounded-full flex items-center justify-center shadow-sm border border-white/50"
                  :class="category.bgColor"
                >
                  <view 
                    class="w-10 h-10 rounded-full bg-gradient-to-br flex items-center justify-center"
                    :class="category.color"
                  >
                    <text class="text-white text-lg font-medium">{{ category.icon }}</text>
                  </view>
                </view>
              </view>
              <text class="text-xs text-gray-700 font-medium">{{ category.name }}</text>
            </view>
          </template>
        </view>
      </scroll-view>
    </view>
    
    <!-- 主体内容区域 -->
    <view class="flex h-[calc(100vh-140px)]">
      <!-- 左侧分类导航 -->
      <view class="w-20 bg-white border-r border-gray-100">
        <!-- 左侧分类骨架屏 -->
        <template v-if="leftCategoriesLoading">
          <view 
            v-for="n in 7" 
            :key="'left-skeleton-' + n"
            class="flex flex-col items-center justify-center py-4 px-2"
          >
            <wd-skeleton
              :width="16"
              :height="16"
              :round="true"
              :animate="true"
            />
            <wd-skeleton
              :width="32"
              :height="10"
              :round="true"
              :animate="true"
              :custom-style="{ marginTop: '4px' }"
            />
            <wd-skeleton
              :width="20"
              :height="8"
              :round="true"
              :animate="true"
              :custom-style="{ marginTop: '2px' }"
            />
          </view>
        </template>
        
        <!-- 左侧分类数据 -->
        <template v-else>
          <view 
            v-for="(category, index) in leftCategories" 
            :key="category.id"
            class="relative flex flex-col items-center justify-center py-4 px-2 border-b border-gray-50 transition-all duration-200 active:bg-blue-50"
            :class="{ 
              'bg-blue-50 border-r-2 border-r-blue-500': active === index,
              'hover:bg-gray-50': active !== index
            }"
            @click="selectLeftCategory(index)"
          >
            <!-- 激活指示器 -->
            <view 
              v-if="active === index" 
              class="absolute left-0 top-1/2 transform -translate-y-1/2 w-1 h-6 bg-blue-500 rounded-r-full"
            ></view>
            
            <!-- 分类图标 -->
            <text class="text-base mb-1" :class="category.icon ? '' : 'hidden'">{{ category.icon }}</text>
            
            <!-- 分类名称 -->
            <text 
              class="text-xs text-center leading-tight font-medium transition-colors"
              :class="active === index ? 'text-blue-600' : (category.color || 'text-gray-700')"
            >
              {{ category.name }}
            </text>
            
            <!-- 商品数量 -->
            <text 
              v-if="category.count" 
              class="text-[10px] text-gray-400 mt-0.5"
            >
              {{ category.count }}
            </text>
          </view>
        </template>
      </view>
      
      <!-- 右侧商品列表 -->
      <scroll-view class="flex-1 bg-white" scroll-y enhanced bounce="false">
        <view class="p-4">
          <!-- 商品列表骨架屏 -->
          <template v-if="productsLoading">
            <view 
              v-for="n in 6" 
              :key="'product-skeleton-' + n"
              class="flex gap-3 py-4 border-b border-gray-100 last:border-b-0"
            >
              <!-- 商品图片骨架 -->
              <wd-skeleton
                :width="80"
                :height="80"
                :round="true"
                :animate="true"
              />
              
              <!-- 商品信息骨架 -->
              <view class="flex-1 space-y-2">
                <wd-skeleton :width="40" :height="16" :round="true" :animate="true" />
                <wd-skeleton :width="240" :height="14" :round="true" :animate="true" />
                <wd-skeleton :width="180" :height="14" :round="true" :animate="true" />
                <wd-skeleton :width="120" :height="12" :round="true" :animate="true" />
                <view class="flex items-center gap-2">
                  <wd-skeleton :width="60" :height="16" :round="true" :animate="true" />
                  <wd-skeleton :width="50" :height="12" :round="true" :animate="true" />
                </view>
              </view>
              
              <wd-skeleton :width="28" :height="28" :round="true" :animate="true" />
            </view>
          </template>
          
          <!-- 商品列表数据 -->
          <template v-else>
            <view 
              v-for="product in products" 
              :key="product.id"
              class="flex gap-3 py-4 border-b border-gray-100 last:border-b-0 active:bg-gray-50 transition-colors"
              @click="goToProductDetail(product.id)"
            >
              <!-- 商品图片 -->
              <view class="relative">
                <image 
                  :src="product.images[0]" 
                  class="w-20 h-20 rounded-lg bg-gray-100 border border-gray-200" 
                  mode="aspectFill"
                />
                
                <!-- 折扣标签 -->
                <view 
                  v-if="product.discount" 
                  class="absolute -top-1 -right-1 px-1.5 py-0.5 rounded-full text-[10px] text-white font-bold"
                  :class="product.tagColor"
                >
                  -{{ product.discount }}%
                </view>
              </view>
              
              <!-- 商品信息 -->
              <view class="flex-1 min-w-0">
                <!-- 商品标签 -->
                <view v-if="product.tag" class="inline-block mb-1">
                  <view 
                    class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] text-white font-bold"
                    :class="product.tagColor"
                  >
                    {{ product.tag }}
                  </view>
                </view>
                
                <!-- 商品名称 -->
                <text class="block text-sm text-gray-800 font-medium leading-5 line-clamp-2 mb-1">
                  {{ product.name }}
                </text>
                
                <!-- 描述信息 -->
                <text class="block text-xs text-gray-500 mb-2">
                  {{ product.description }}
                </text>
                
                <!-- 评价和销量 -->
                <view class="flex items-center gap-3 mb-2">
                  <view class="flex items-center gap-1">
                    <text class="text-[10px] text-yellow-500">★</text>
                    <text class="text-[10px] text-gray-600">{{ product.rating }}</text>
                  </view>
                  <text class="text-[10px] text-gray-500">已售{{ product.sales }}</text>
                  <text class="text-[10px] text-gray-500">库存{{ product.stock }}</text>
                </view>
                
                <!-- 价格信息 -->
                <view class="flex items-end gap-2">
                  <text class="text-lg font-bold text-red-500">
                    ￥{{ formatPriceDisplay(product.currentPrice) }}
                  </text>
                  <text 
                    v-if="product.originalPrice && product.originalPrice > product.currentPrice"
                    class="text-xs text-gray-400 line-through"
                  >
                    ￥{{ formatPriceDisplay(product.originalPrice) }}
                  </text>
                  <text 
                    v-if="product.priceLabel"
                    class="text-[10px] px-1.5 py-0.5 bg-red-50 text-red-600 rounded"
                  >
                    {{ product.priceLabel }}
                  </text>
                </view>
              </view>
              
              <!-- 添加按钮 -->
              <view 
                class="w-7 h-7 bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg flex items-center justify-center shadow-sm active:scale-95 transition-transform"
                @click.stop="addToCart(product)"
              >
                <wd-icon name="add" size="14px" color="white" />
              </view>
            </view>
          </template>
          
          <!-- 空状态 -->
          <view v-if="!productsLoading && products.length === 0" class="text-center py-20">
            <view class="w-20 h-20 mx-auto mb-4 bg-gray-100 rounded-lg flex items-center justify-center">
              <wd-icon name="goods" size="32px" color="#d1d5db" />
            </view>
            <text class="text-gray-500 text-sm">暂无商品</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<route lang="json">
{
  "name": "category",
  "layout": "tabbar",
  "style": {
    "navigationBarTitleText": "商品分类",
    "navigationBarBackgroundColor": "#ffffff",
    "navigationBarTextStyle": "black"
  }
}
</route>